#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netdb.h>

#define SERV_PORT 9877

int main() {
    int listen_fd, conn_fd;
    struct sockaddr_in serv_addr, cli_addr;
    socklen_t cli_len;
    char buf[4096];

    listen_fd = socket(AF_INET, SOCK_STREAM, 0);

    bzero(&serv_addr, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    serv_addr.sin_port = htons(SERV_PORT);

    bind(listen_fd, (struct sockaddr *)&serv_addr, sizeof(serv_addr));

    listen(listen_fd, 5);
  struct {
        u_int32_t message_length;
        u_int32_t message_type;
        char buf[128];
    } message;
    for (;;) {
        cli_len = sizeof(cli_addr);
        conn_fd = accept(listen_fd, (struct sockaddr *)&cli_addr, &cli_len); // 成功返回，客户端才算连接成功

        ssize_t n;
        while ((n = read(conn_fd, &message, sizeof(message))) > 0) {
            // Convert the received integers to the host byte order
            message.message_length = ntohl(message.message_length);
            message.message_type = ntohl(message.message_type);

            // Print the message details
            printf("Message length: %u\n", message.message_length);
            printf("Message type: %u\n", message.message_type);
            printf("Message content: %.*s\n", (int)sizeof(message.buf), message.buf);

            // Send the received data back to the client
            write(conn_fd, &message, n);
            memset(&message, 0, sizeof message);
        }

        close(conn_fd);
    }

    return 0;
}
